<template>
  <div class="metadata-container">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 数据中心管理 -->
      <el-tab-pane label="数据中心管理" name="dataCenter">
        <div class="table-operations">
          <el-button type="primary" @click="handleAddDataCenter">新增数据中心</el-button>
        </div>
        <el-table :data="dataCenterList" border style="width: 100%" v-loading="loading" size="default">
          <el-table-column prop="code" label="数据中心编码" min-width="100" />
          <el-table-column prop="name" label="数据中心名称" min-width="100" />
          <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
          <el-table-column prop="domain" label="访问域名" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.domain || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="140" show-overflow-tooltip />
          <el-table-column prop="updateTime" label="更新时间" min-width="140" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="handleEditDataCenter(scope.row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDeleteDataCenter(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 数据库实例管理 -->
      <el-tab-pane label="数据库实例管理" name="dataInstance">
        <div class="table-operations">
          <el-button type="primary" @click="handleAddInstance">新增实例</el-button>
        </div>
        <el-table :data="instanceList" border style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="数据源名称" />
          <el-table-column prop="type" label="数据源类型" />
          <el-table-column prop="dataCenter" label="数据中心" />
          <el-table-column prop="instance" label="实例名称" />
          <el-table-column prop="host" label="主机地址" />
          <el-table-column prop="registHost" label="注册中心地址" />
          <el-table-column prop="port" label="端口号" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEditInstance(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDeleteInstance(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 任务模板管理 -->
      <el-tab-pane label="任务模板管理" name="template">
        <div class="table-operations">
          <el-button type="primary" @click="handleAddTemplate">新增配置</el-button>
        </div>
        <el-table :data="templateList" border style="width: 100%" v-loading="loading" size="default">
          <el-table-column prop="name" label="配置名称" min-width="120" />
          <el-table-column prop="template" label="配置内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip />
          <el-table-column prop="updateTime" label="更新时间" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="handleEditTemplate(scope.row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDeleteTemplate(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 数据中心表单对话框 -->
    <el-dialog
      v-model="dataCenterDialog.visible"
      :title="dataCenterDialog.type === 'add' ? '新增数据中心' : '编辑数据中心'"
      width="500px"
    >
      <el-form
        ref="dataCenterFormRef"
        :model="dataCenterForm"
        :rules="dataCenterRules"
        label-width="100px"
      >
        <el-form-item label="数据中心编码" prop="code">
          <el-input v-model="dataCenterForm.code" placeholder="请输入数据中心编码" />
        </el-form-item>
        <el-form-item label="数据中心名称" prop="name">
          <el-input v-model="dataCenterForm.name" placeholder="请输入数据中心名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="dataCenterForm.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="访问域名" prop="domain">
          <el-input v-model="dataCenterForm.domain" placeholder="请输入访问域名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="dataCenterForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dataCenterDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitDataCenterForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据库实例表单对话框 -->
    <el-dialog
      v-model="instanceDialog.visible"
      :title="instanceDialog.type === 'add' ? '新增实例' : '编辑实例'"
      width="500px"
    >
      <el-form
        ref="instanceFormRef"
        :model="instanceForm"
        :rules="instanceRules"
        label-width="100px"
      >
        <el-form-item label="自定义名称" prop="name">
          <el-input v-model="instanceForm.name" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="instanceForm.type" placeholder="请选择数据源类型">
            <el-option label="MySQL" value="MySQL" />
            <el-option label="Starrocks" value="Starrocks" />
            <el-option label="TiDB" value="TiDB" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据中心" prop="dataCenter">
          <el-select v-model="instanceForm.dataCenter" placeholder="请选择数据中心">
            <el-option
              v-for="item in dataCenterOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="实例名称" prop="instance">
          <el-input v-model="instanceForm.instance" placeholder="请输入实例名称" />
        </el-form-item>
        <el-form-item label="注册中心地址" prop="registHost">
          <el-input v-model="instanceForm.registHost" placeholder="注册中心地址,非必填项" />
        </el-form-item>
        <el-form-item label="访问地址" prop="host">
          <el-input v-model="instanceForm.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="访问端口" prop="port">
          <el-input-number v-model="instanceForm.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="instanceForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="instanceForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="instanceDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitInstanceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 配置模板表单对话框 -->
    <el-dialog
      v-model="templateDialog.visible"
      :title="templateDialog.type === 'add' ? '新增配置' : '编辑配置'"
      width="800px"
      destroy-on-close
    >
      <el-form ref="templateFormRef" :model="templateForm" :rules="templateRules" label-width="100px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置内容" prop="template">
          <el-input
            v-model="templateForm.template"
            type="textarea"
            :rows="10"
            placeholder="请输入配置内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitTemplateForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDataCenterList,
  createDataCenter,
  updateDataCenter,
  deleteDataCenter,
  getInstanceList,
  createInstance,
  updateInstance,
  deleteInstance,
  getTemplateList,
  createTemplate,
  updateTemplate,
  deleteTemplate
} from '@/api/metadata'

// 当前激活的标签页
const activeTab = ref('dataCenter')

// 加载状态
const loading = ref(false)

// 数据中心相关
const dataCenterList = ref([])
const dataCenterOptions = ref([])
const dataCenterDialog = reactive({
  visible: false,
  type: 'add'
})
const dataCenterForm = reactive({
  code: '',
  name: '',
  description: '',
  domain: '',
  status: 1
})
const dataCenterRules = {
  code: [{ required: true, message: '请输入数据中心编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入数据中心名称', trigger: 'blur' }],
  domain: [{ required: true, message: '请输入访问域名', trigger: 'blur' }]
}

// 数据库实例相关
const instanceList = ref([])
const instanceDialog = reactive({
  visible: false,
  type: 'add'
})
const instanceForm = reactive({
  name: '',
  type: '',
  dataCenter: '',
  instance: '',
  host: '',
  port: 3306,
  username: '',
  password: ''
})
const instanceRules = {
  name: [{ required: true, message: '请输入数据源名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据源类型', trigger: 'change' }],
  dataCenter: [{ required: true, message: '请选择数据中心', trigger: 'change' }],
  instance: [{ required: true, message: '请输入实例名称', trigger: 'blur' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 配置模板相关
const templateList = ref([])
const templateOptions = ref([])
const templateDialog = ref({
  visible: false,
  type: 'add'
})
const templateForm = ref({
  name: '',
  template: '',
  dataCenterIds: ''
})
const templateRules = {
  name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
  template: [{ required: true, message: '请输入配置内容', trigger: 'blur' }]
}

// 获取数据中心名称
const getDataCenterName = (code) => {
  const center = dataCenterOptions.value.find(item => item.code === code)
  return center ? center.name : code
}

// 数据中心相关方法
const handleAddDataCenter = () => {
  dataCenterDialog.type = 'add'
  dataCenterDialog.visible = true
  Object.assign(dataCenterForm, {
    code: '',
    name: '',
    description: '',
    domain: '',
    status: 1
  })
}

const handleEditDataCenter = (row) => {
  dataCenterDialog.type = 'edit'
  dataCenterDialog.visible = true
  Object.assign(dataCenterForm, row)
}

const handleDeleteDataCenter = (row) => {
  ElMessageBox.confirm('确认删除该数据中心吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDataCenter(row.id)
      ElMessage.success('删除成功')
      fetchDataCenterList()
    } catch (error) {
      console.error('删除数据中心失败：', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}

const submitDataCenterForm = async () => {
  try {
    const isCreate = dataCenterDialog.type === 'add'
    const formData = { ...dataCenterForm }
    if (isCreate) {
      delete formData.id
    }
    const request = isCreate ? createDataCenter(formData) : updateDataCenter(formData)
    await request
    ElMessage.success(isCreate ? '创建成功' : '更新成功')
    dataCenterDialog.visible = false
    fetchDataCenterList()
  } catch (error) {
    console.error('保存数据中心失败：', error)
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  }
}

// 数据库实例相关方法
const handleAddInstance = () => {
  instanceDialog.type = 'add'
  instanceDialog.visible = true
  Object.assign(instanceForm, {
    name: '',
    type: '',
    dataCenter: '',
    instance: '',
    host: '',
    port: 3306,
    username: '',
    password: ''
  })
}

const handleEditInstance = (row) => {
  instanceDialog.type = 'edit'
  instanceDialog.visible = true
  Object.assign(instanceForm, row)
}

const handleDeleteInstance = (row) => {
  ElMessageBox.confirm('确认删除该实例吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteInstance(row.id)
      ElMessage.success('删除成功')
      fetchInstanceList()
    } catch (error) {
      console.error('删除实例失败：', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}

const submitInstanceForm = async () => {
  try {
    const isCreate = instanceDialog.type === 'add'
    const formData = { ...instanceForm }
    if (isCreate) {
      delete formData.id
    }
    const request = isCreate ? createInstance(instanceForm) : updateInstance(instanceForm)
    await request
    ElMessage.success(isCreate ? '创建成功' : '更新成功')
    instanceDialog.visible = false
    fetchInstanceList()
  } catch (error) {
    console.error('保存实例失败：', error)
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  }
}

// 配置模板相关方法
const handleAddTemplate = () => {
  templateDialog.value.type = 'add'
  templateDialog.value.visible = true
  Object.assign(templateForm.value, {
    name: '',
    template: '',
    dataCenterIds: ''
  })
}

const handleEditTemplate = (row) => {
  templateDialog.value.type = 'edit'
  templateDialog.value.visible = true
  Object.assign(templateForm.value, row)
}

const handleDeleteTemplate = (row) => {
  ElMessageBox.confirm('确认删除该配置吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTemplate(row.id)
      ElMessage.success('删除成功')
      fetchTemplateList()
    } catch (error) {
      console.error('删除配置失败：', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}

const submitTemplateForm = async () => {
  try {
    const isCreate = templateDialog.value.type === 'add'
    const formData = { ...templateForm.value }
    if (isCreate) {
      delete formData.id
    }
    const request = isCreate ? createTemplate(formData) : updateTemplate(formData)
    await request
    ElMessage.success(isCreate ? '创建成功' : '更新成功')
    templateDialog.value.visible = false
    fetchTemplateList()
  } catch (error) {
    console.error('保存配置失败：', error)
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  }
}

// 数据加载方法
const fetchDataCenterList = async () => {
  try {
    loading.value = true
    const response = await getDataCenterList()
    dataCenterList.value = response || []
    dataCenterOptions.value = dataCenterList.value.map(item => ({
      code: item.code,
      name: item.name
    }))
  } catch (error) {
    console.error('获取数据中心列表失败：', error)
    ElMessage.error('获取数据中心列表失败')
  } finally {
    loading.value = false
  }
}

const fetchInstanceList = async () => {
  try {
    loading.value = true
    const response = await getInstanceList()
    instanceList.value = response || []
  } catch (error) {
    console.error('获取实例列表失败：', error)
    ElMessage.error('获取实例列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTemplateList = async () => {
  try {
    loading.value = true
    const response = await getTemplateList()
    templateList.value = response || []
    templateOptions.value = response.map(item => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取模板列表失败：', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  switch (newTab) {
    case 'dataCenter':
      fetchDataCenterList()
      break
    case 'dataInstance':
      fetchInstanceList()
      break
    case 'template':
      fetchTemplateList()
      break
  }
})

onMounted(() => {
  fetchDataCenterList()
  fetchTemplateList()
})
</script>

<style scoped>
.metadata-container {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-operations {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.mx-1 {
  margin: 0 4px;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-button--small) {
  padding: 4px 8px;
}

:deep(.el-tag--small) {
  padding: 0 6px;
  height: 20px;
  line-height: 18px;
}
</style>